<!--2018/12/28 23:26. by soft-->
<#assign title='评分条目列表'>
<#include '../header.ftl'>

<style>
  .label {
    display: inline-block;
    position: relative;
    font-size: 11px;
    padding: 5px 12px 5px 5px;
    margin: 6px 5px 0 0;
    cursor: pointer;
    border-radius: 5px;
  }

  .label .close {
    position: absolute;
    text-align: center;
    line-height: 13px;
    height: 14px;
    width: 14px;
    right: -4px;
    top: -4px;
    font-size: 15px;
    background-color: #b40020;
    border-radius: 50%;
    transition: transform .3s;
  }

  .label .close:hover {
    transform: rotate(45deg);
  }

  #ranks-box, #places-box {
    cursor: crosshair;
    min-height: 38px;
    height: auto;
    padding-bottom: 4px;
  }
</style>

<#--级别模板-->
<script type="text/html" id="rank-tpl">
  <div class="rank layui-bg-cyan label" onmouseover="methods.showRank(event);">
    <span class="close" title="点击删除" onclick="methods.deleteRank(event);" data-index="{{d.index}}">&xotime;</span>
    {{d.name}}
  </div>
</script>
<#--地位模板-->
<script type="text/html" id="place-tpl">
  <div class="place layui-bg-blue label" onmouseover="methods.showPlace(event);">
    <span class="close" title="点击删除" onclick="methods.deletePlace(event);" data-index="{{d.place - 1}}">&xotime;</span>
    {{getPos(d.place)}}
  </div>
</script>
<#--item添加/修改模板-->
<script type="text/html" id="items-tpl">
  <div class="model-padding">
    <form class="layui-form" lay-filter="items-form">
      <input type="hidden" name="id" value="{{d.id||''}}">
      <div class="layui-col-sm12 layui-col-xs12">
        <div class="layui-form-item">
          <label class="layui-form-label">项目名</label>
          <div class="layui-input-block">
            <input name="name" placeholder="请输入项目名" class="layui-input" value="{{d.name||''}}"
                   lay-verType="tips" lay-verify="required">
          </div>
        </div>
      </div>
      <div class="layui-col-sm12 layui-col-xs12">
        <#--开关选项-->
        <div class="layui-col-sm6 layui-col-xs6">
          <div class="layui-form-item">
            <label class="layui-form-label">需要结项</label>
            <div class="layui-input-block">
              <input type="checkbox" name="needEnd" value="true" lay-skin="switch" lay-text="需要|不需" {{d.needEnd?'checked':''}}>
            </div>
          </div>
        </div>
        <div class="layui-col-sm6 layui-col-xs6">
          <div class="layui-form-item">
            <label class="layui-form-label">自填分值</label>
            <div class="layui-input-block">
              <input type="checkbox" name="canWrite" value="true" lay-skin="switch" lay-text="允许|禁止" {{d.canWrite?'checked':''}}>
            </div>
          </div>
        </div>
        <div class="layui-col-sm6 layui-col-xs6">
          <div class="layui-form-item">
            <label class="layui-form-label">是否加分</label>
            <div class="layui-input-block">
              <input type="checkbox" name="isAdd" value="true" lay-skin="switch" lay-text="加分|减分" {{d.isAdd?'checked':''}}>
            </div>
          </div>
        </div>
        <div class="layui-col-sm6 layui-col-xs6">
          <div class="layui-form-item">
            <label class="layui-form-label">唯一</label>
            <div class="layui-input-block">
              <input type="checkbox" name="needEnd" value="true" lay-skin="switch" lay-text="是|否" {{d.only?'checked':''}}>
            </div>
          </div>
        </div>
        <#--开关选项结束-->
      </div>

      <div class="layui-col-sm12 layui-col-xs12">
        <div class="layui-form-item">
          <label class="layui-form-label">项目分值</label>
          <div class="layui-input-block">
            <input name="maxScore" lay-verType="tips" lay-verify="required|number" value="{{d.maxScore||''}}"
                   placeholder="请输入项目最大分值" class="layui-input">
          </div>
        </div>
      </div>

      <div class="layui-col-sm12 layui-col-xs12">
        <div class="layui-form-item">
          <label class="layui-form-label">项目分类</label>
          <div class="layui-input-block">
            <div onclick="methods.addRank(this);" id="ranks-box" class="layui-input">
              {{# layui.each(d.ranks, function(index, im) { }}
              <div class="rank layui-bg-cyan label" onmouseover="methods.showRank(event);">
                  <span class="close" title="点击删除"
                        onclick="methods.deleteRank(event);" data-index="{{index}}">&xotime;</span>
                {{im.name}}
              </div>
              {{# }); }}
            </div>
          </div>
        </div>
      </div>

      <div class="layui-col-sm12 layui-col-xs12">
        <div class="layui-form-item">
          <label class="layui-form-label">项目人员</label>
          <div class="layui-input-block">
            <div onclick="methods.addPlace(this);" id="places-box" class="layui-input">
              {{# layui.each(d.places, function(index, im) { }}
              <div class="place layui-bg-blue label" onmouseover="methods.showPlace(event);">
                  <span class="close" title="点击删除"
                        onclick="methods.deletePlace(event);" data-index="{{index}}">&xotime;</span>
                {{getPos(im.place)}}
              </div>
              {{# }); }}
            </div>
          </div>
        </div>
      </div>
      <div class="layui-col-sm12 layui-col-xs12">
        <div class="layui-form-item">
          <label class="layui-form-label">项目描述</label>
          <div class="layui-input-block">
            <textarea name="comment" style="resize: none;" class="layui-textarea" placeholder="项目的描述"
                      lay-verType="tips" lay-verify="required|comment">{{d.comment||''}}</textarea>
          </div>
        </div>
      </div>

      <div class="layui-col-sm12 layui-col-xs12">
        <div class="layui-form-item">
          <div class="layui-input-block text-right">
            {{# if (d.type === 'add_') { }}
            <button class="layui-btn layui-btn-normal layui-btn-sm" lay-submit lay-filter="addItem">添加</button>
            {{# } else if (d.type === 'edit_') { }}
            <button class="layui-btn layui-btn-sm" lay-submit lay-filter="editItem">修改</button>
            {{# } }}
          </div>
        </div>
      </div>
    </form>
  </div>
</script>

<#--地位添加模板-->
<script type="text/html" id="place-ac-tpl">
  <div class="layui-card" style="padding-right: 20px;">
    <div class="layui-card-header" style="padding-left: 10px;">
      <span class="layui-badge layui-bg-green">地位：{{getPos(d.place)}}</span>
      <span class="layui-badge layui-bg-red">提示：分值存在则以分值为准！</span>
    </div>
    <div class="layui-card-body layui-row">
      <form class="layui-form" lay-filter="place-ac-tpl">
        <div class="layui-col-sm12 layui-col-xs12">
          <div class="layui-form-item">
            <label class="layui-form-label">输入分值</label>
            <div class="layui-input-block">
              <input name="score" type="number" class="layui-input" placeholder="分值"
                     lay-verType="tips" lay-verify="score">
            </div>
          </div>
        </div>
        <div class="layui-col-sm12 layui-col-xs12">
          <div class="layui-form-item">
            <label class="layui-form-label">分值比率</label>
            <div class="layui-input-block">
              <input name="ratio" type="number" class="layui-input" placeholder="分值比率"
                     lay-verType="tips" lay-verify="ratio">
            </div>
          </div>
        </div>

        <div class="layui-col-sm12 layui-col-xs12">
          <div class="layui-form-item">
            <div class="layui-input-block">
              <button class="layui-btn layui-btn-sm layui-btn-fluid layui-btn-normal" lay-submit lay-filter="addPlace">
                添加
              </button>
            </div>
          </div>
        </div>
      </form>
    </div>
  </div>
</script>
<#--级别/分类添加模板-->
<script type="text/html" id="rank-ac-tpl">
  <div class="layui-row model-padding">
    <form class="layui-form" lay-filter="rank-ac-tpl">
      <div class="layui-col-sm12 layui-col-xs12">
        <div class="layui-form-item">
          <label class="layui-form-label">分类名</label>
          <div class="layui-input-block">
            <input name="name" class="layui-input" placeholder="输入分类名"
                   lay-verType="tips" lay-verify="required">
          </div>
        </div>
      </div>
      <div class="layui-col-sm12 layui-col-xs12">
        <div class="layui-form-item">
          <label class="layui-form-label">输入分值</label>
          <div class="layui-input-block">
            <input name="score" type="number" class="layui-input" placeholder="分值"
                   lay-verType="tips" lay-verify="score">
          </div>
        </div>
      </div>
      <div class="layui-col-sm12 layui-col-xs12">
        <div class="layui-form-item">
          <label class="layui-form-label">分值比率</label>
          <div class="layui-input-block">
            <input name="ratio" type="number" class="layui-input" placeholder="分值比率"
                   lay-verType="tips" lay-verify="ratio">
          </div>
        </div>
      </div>
      <div class="layui-col-sm12 layui-col-xs12">
        <div class="layui-form-item text-right">
          <div style="margin-left: 110px;">
            <span class="layui-badge layui-bg-red">提示：分值存在则以分值为准！</span>
          </div>
        </div>
      </div>
      <div class="layui-col-sm12 layui-col-xs12">
        <div class="layui-form-item">
          <div class="layui-input-block">
            <button class="layui-btn layui-btn-sm layui-btn-fluid" lay-submit lay-filter="addRank">添加</button>
          </div>
        </div>
      </div>
    </form>
  </div>
</script>

<#--主体部分-->
<div class="items_">
  <div class="layui-card">
    <div class="layui-card-header">
      <div class="text-right">
        <button class="layui-btn layui-btn-sm layui-btn-normal" onclick="methods.addItem();">添加</button>
      </div>
    </div>
    <div class="layui-card-body">
      <table id="items-table"></table>

      <script type="text/html" id="record-tool">
        <a class="layui-btn layui-btn-xs" lay-event="editItem">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delItem">删除</a>
      </script>
    </div>
  </div>

  <script>
    var $BOX; // 添加的分类和地位将要放在的容器dom
    var rank = {}; // 用于保存将要添加的项目中的所有分类
    var place = {}; // 用户保存将要添加的项目中的所有地位
    var mainIndex, childIndex;
    var methods;
    layui.use(['table', 'layer', 'jquery', 'laytpl', 'form'], function () {
      var $ = layui.$;
      var form = layui.form;
      var layer = layui.layer;
      var table = layui.table;
      var laytpl = layui.laytpl;
      var $items = $('#items-tpl');
      var $place = $('#place-tpl');
      var $placeAc = $('#place-ac-tpl');
      var $rank = $('#rank-tpl');
      var $rankAc = $('#rank-ac-tpl');

      table.render({
        elem: '#items-table',
        url: '/item/page',
        method: 'post',
        page: true,
        cols: [[
          {title: '序号', type: 'numbers'},
          {field: 'name', title: '项目名'},
          {
            title: '自填分值',
            width: 90,
            templet: "<i>{{d.canWrite?'<b class=\"layui-badge layui-bg-cyan\">允许</b>':" +
            "'<b class=\"layui-badge layui-bg-gray\">禁止</b>'}}</i>"
          },
          {
            title: '是否加分',
            width: 90,
            templet: "<i>{{d.isAdd?'<b class=\"layui-badge layui-bg-green\">加分</b>':" +
            "'<b class=\"layui-badge\">减分</b>'}}</i>"
          },
          {
            title: '需要结项',
            width: 90,
            templet: "<i>{{d.needEnd?'<b class=\"layui-badge layui-bg-cyan\">需要</b>':" +
            "'<b class=\"layui-badge layui-bg-gray\">不需要</b>'}}</i>"
          },
          {
            title: '唯一',
            templet: "<i>{{d.only?'<b class=\"layui-badge layui-bg-green\">是</b>':" +
            "'<b class=\"layui-badge layui-bg-orange\">否</b>'}}</i>"
          },
          {field: 'rankNum', title: '级别数', width: 75},
          {field: 'peopleNum', title: '允许人数'},
          {field: 'maxScore', title: '最大分值'},
          {field: 'datetime', title: '发布时间', width: 120},
          {title: '操作', toolbar: '#record-tool'}
        ]],
        parseData: function (res) {
          return {
            code: 0,
            msg: res.message,
            count: (res.payload ? res.payload.totalElements : 0),
            data: (res.payload ? res.payload.content : 0)
          }
        }
      });

      methods = {
        addRank: function (self) {
          if (rank[mainIndex] == null) rank[mainIndex] = [];
          $BOX = $(self);
          laytpl($rankAc.html()).render({}, function (html) {
            childIndex = layer.open({
              type: 1,
              title: '分类添加',
              area: ['380px', '305px'],
              content: html
            });
          });
        },
        deleteRank: function (e) {
          e.stopPropagation();
          var self = $(e.target);
          var index = self.data('index');
          var ranks = rank[mainIndex];
          ranks.splice(index, 1);
          self.parent('.rank').remove();
        },
        showRank: function (e) {
          e.stopPropagation();
          var self = $(e.target);
          var rk = rank[mainIndex][self.children('span').data('index')];
          layer.tips('<div class="text-center">' +
              '<b class="layui-badge">比率: ' + parseFloat(0 + rk.ratio) + '</b><br>' +
              '<b class="layui-badge layui-bg-blue">分值: ' + parseInt(0 + rk.score) + '</b>' +
              '</div>', self, {tips: [1, '#6f6f6f'], time: 1200});
        },
        addPlace: function (self) {
          if (place[mainIndex] == null) place[mainIndex] = [];
          $BOX = $(self);
          laytpl($placeAc.html()).render({place: place[mainIndex].length + 1}, function (html) {
            childIndex = layer.open({
              type: 1,
              title: '地位添加',
              area: ['380px', '266px'],
              content: html
            });
          });
        },
        deletePlace: function (e) {
          e.stopPropagation();
          var self = $(e.target);
          var index = self.data('index');
          var places = place[mainIndex];
          places.splice(index, 1);
          self.parent('.place').remove();
        },
        showPlace: function (e) {
          e.stopPropagation();
          var self = $(e.target);
          var pe = place[mainIndex][self.children('span').data('index')];
          layer.tips('<div>' +
              '<b class="layui-badge">比率: ' + parseFloat(0 + pe.ratio) + '</b><br>' +
              '<b class="layui-badge layui-bg-blue">分值: ' + parseInt(0 + pe.score) + '</b>' +
              '</div>', self, {tips: [1, '#a6a6a6'], time: 1200});
        },
        addItem: function () {
          laytpl($items.html()).render({isAdd: true, type: "add_"}, function (html) {
            mainIndex = layer.open({
              type: 1,
              title: '项目添加',
              move: false,
              area: ['500px'],
              content: html,
              success: function () {
                place = {};
                rank = {};
              }
            });
            form.render();
          });
        },
        delItem: function (item) {
          layer.confirm('确定删除<b style="color: #910000;">[' + item.name + ']</b>吗？', {icon: 3}, function (index) {
            $.post('${root}/item/delete/' + item.id, function (data) {
              if (data.status === 200) {
                layer.msg('删除成功！', {icon: 6, time: 1200});
                table.reload('items-table');
              } else {
                layer.alert('ERROR: ' + data.message, {title: '删除失败:', icon: 2});
              }
              layer.close(index);
            });
          });
        },
        editItem: function (obj) {
          var item = $.extend(true, {type: "edit_"}, obj); // 深拷贝 不至于等级/地位被删除而改变原数据
          laytpl($items.html()).render(item, function (html) {
            mainIndex = layer.open({
              type: 1,
              title: '项目编辑',
              move: false,
              area: ['500px'],
              content: html,
              success: function () {
                place = {};
                rank = {};
              }
            });
            form.render();
          });
          rank[mainIndex] = item.ranks;
          place[mainIndex] = item.places;
        }
      };
      table.on('tool', function (o) {
        var mtd = methods[o.event];
        if (mtd != null) {
          mtd(o.data);
        }
      });

      function updateFd(fd) {
        if (fd.isAdd == null) fd.isAdd = 'false';
        if (fd.needEnd == null) fd.needEnd = 'false';
        if (fd.canWrite == null) fd.canWrite = 'false';
        return fd;
      }
      //以json格式将数据传送到后端 完成项目的添加
      form.on('submit(addItem)', function (obj) {
        var fd = obj.field;
        updateFd(fd);
        console.log(fd);
        fd.ranks = rank[mainIndex];
        fd.places = place[mainIndex];
        postJson('${root}/item/add', fd, function (data) {
          if (data.status === 200) {
            layer.msg('添加成功！', {icon: 6, time: 1200});
            table.reload('items-table');
          } else {
            layer.alert('ERROR: ' + data.message, {title: '添加失败:', icon: 2});
          }
          layer.close(mainIndex);
          // 释放数据
          rank[mainIndex] = null;
          place[mainIndex] = null;
        });
        return false;
      });

      form.on('submit(editItem)', function (obj) {
        var fd = obj.field;
        updateFd(fd);
        fd.ranks = rank[mainIndex];
        fd.places = place[mainIndex];
        postJson('${root}/item/change', fd, function (data) {
          if (data.status === 200) {
            layer.msg('修改成功！', {icon: 6, time: 1200});
            table.reload('items-table');
          } else {
            layer.alert('ERROR: ' + data.message, {title: '修改失败:', icon: 2});
          }
          layer.close(mainIndex);
          // 释放数据
          rank[mainIndex] = null;
          place[mainIndex] = null;
        });
        return false;
      });

      // 添加项目的分类 添加在数组中
      form.on('submit(addRank)', function (obj) {
        var fd = obj.field;
        var ranks = rank[mainIndex];
        fd.index = ranks.length;
        ranks.push(fd);
        laytpl($rank.html()).render(fd, function (html) {
          $BOX.append(html);
        });
        layer.close(childIndex);
        return false;
      });

      // 添加项目地位 添加在数组中
      form.on('submit(addPlace)', function (obj) {
        var fd = obj.field;
        var places = place[mainIndex];
        fd.place = places.length + 1;
        places.push(fd);
        laytpl($place.html()).render(fd, function (html) {
          $BOX.append(html);
        });
        layer.close(childIndex);
        return false;
      });

      form.verify({
        score: function (val, elem) {
          if (empty(val) && ratioEmpty()) {
            return "分数和比率不能同时为空！";
          }

          function ratioEmpty() {
            var rv = $(elem).parents('form').find('[name=ratio]').val();
            return empty(rv);
          }
        },
        ratio: function (val, elem) {
          if (empty(val) && scoreEmpty()) {
            return "分数和比率不能同时为空！";
          } else if (!empty(val)) {
            if (val < -1 || val > 1) {
              return "比率必须在-1到1之间！";
            }
          }

          function scoreEmpty() {
            var sv = $(elem).parents('form').find('[name=score]').val();
            return empty(sv);
          }
        },
        comment: function (val, elem) {
          if (empty(val)) {
            return "必填项不能为空！";
          }
        }
      });

      function empty(val) {
        return (val == null || val.trim().length === 0);
      }

      function postJson(url, data, success) {
        $.ajax({
          url: url,
          type: 'POST',
          contentType: "application/json",
          data: JSON.stringify(data),
          success: success
        });
      }
    });
  </script>
</div>

<#include '../footer.ftl'>
